//
//  HomeViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/18.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "HomeViewController.h"
#import "TableViewHeader.h"
#import "ActiveHeaderView.h"
#import "HomeTableViewCell.h"
#import "CouponView.h"
#import "GoodsDetailsViewController.h"
#import "GoodsModel.h"
//#import <CoreLocation/CoreLocation.h>
#import <JMessage/JMessage.h>
#import "CalenderViewController.h"
#import "SearchGoodsListViewController.h"
#import "AppDelegate.h"
#import "BannerModel.h"
#import "BannerWebViewViewController.h"
#import "ShopDetailsViewController.h"
#import <CoreLocation/CoreLocation.h>


@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,HomeCouponViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIView * backView;
@property (nonatomic, strong)CouponView * couponView;
@property (nonatomic, strong)NSArray<GoodsModel *> * goodlistArray;

@property (nonatomic, strong) CLLocationManager *locationManager;
//@property (nonatomic, strong)CLLocation * userLocation;
//@property(strong,nonatomic)UIWindow *window;
//@property(strong,nonatomic)UIButton *button;
@property (nonatomic, weak)UILabel * showLabel;
@property (nonatomic, copy)NSString * ID;
@property (nonatomic, assign)int count;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ZRWhiteColor;
    self.count = 1;
    
    self.goodlistArray = [NSArray bg_arrayWithName:@"homeGoods"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeGoodsListData:) name:@"changeGoodsListData" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToBannerView:) name:@"pushToBannerView" object:nil];
    
    [self startLocation];
    [self setupNav];
    [self setupNSNoti];
    [self setupUI];
//    [self createButton];
}

- (void)setGoodlistArray:(NSArray<GoodsModel *> *)goodlistArray{
    
    _goodlistArray = goodlistArray;
    
    [self.tableView reloadData];
}

- (void)setupNav{
    
//    UIButton * leftButton = [[UIButton alloc] init];
//    
//    [leftButton setImage:[UIImage imageNamed:@"discount"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(didLeftNavButton) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem * leftBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    
//    self.navigationItem.leftBarButtonItem = leftBar;
    
    
    UIButton * rightButton = [[UIButton alloc] init];
    
    [rightButton setImage:[UIImage imageNamed:@"search(2)"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didRightNavButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
    
    
    UIView * titleView = [[UIView new] initWithFrame:CGRectMake(0, 0, 100 * SCREENH6, 50 * SCREENH6)];
    
    UIImageView * titleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-23 * SCREENH6, -15 * SCREENH6, 50 * SCREENH6, 36 * SCREENH6)];
    titleImageView.image = [UIImage imageNamed:@"logo"];
    [titleView addSubview:titleImageView];

    self.navigationItem.titleView = titleView;

    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getUserInfoResultWithUser_id:user_id WithExamine_user_id:@"" WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res===%@",responseData);
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            NSString * phone = [NSString stringWithFormat:@"%@",dict[@"phone"]];
            NSString * user_name = [NSString stringWithFormat:@"%@",dict[@"user_name"]];
            int jiguang_register_status = [dict[@"jiguang_register_status"] intValue];
            
            NSString * imgStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,dict[@"head_img"]];
            DEF_SET_OBJECT(imgStr, @"imgStr");
            DEF_SET_OBJECT(phone, @"phone");
            DEF_SET_OBJECT(user_name, @"name");
            
            NSURL * url = [NSURL URLWithString:imgStr];
            //            UIImage * imaa = [UIImage ];
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            if (jiguang_register_status == 1) {
                
                [JMSGUser loginWithUsername:phone password:phone completionHandler:^(id resultObject, NSError *error) {
                    
                    if (error == nil) {

                        NSLog(@"===登录成功");
                    }else{
                        
                        NSLog(@"error===%@",error);
                        
                    }
                }];
            }else{
                
                JMSGUserInfo *info = [[JMSGUserInfo alloc]init];
                info.nickname = user_name;
                
                [JMSGUser registerWithUsername:phone password:phone userInfo:info completionHandler:^(id resultObject, NSError *error) {
                    if (!error) {
                        //注册成功
                        [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"jiguang_register_status" WithUpdate_content:@"1" WithBlock:^(BOOL success, id responseData) {
                            
                            if (success) {
                                
//                                NSLog(@"===注册成功");
                            }
                        }];
                    } else {
                        //注册失败
//                        NSLog(@"error==%@",error);
                    }
                }];
            }
            
            [JMSGUser updateMyInfoWithParameter:user_name userFieldType:kJMSGUserFieldsNickname completionHandler:^(id resultObject, NSError *error) {
                
                if (error == nil) {
                    
//                                        NSLog(@"===修改成功");
                    
                } else {
//                                        NSLog(@"===修改失败");
                    
                }
            }];
            
            [JMSGUser updateMyInfoWithParameter:data userFieldType:kJMSGUserFieldsAvatar completionHandler:^(id resultObject, NSError *error) {
                
                if (error == nil) {
                                        NSLog(@"===shanghcuan");
                    //                    [MBProgressHUD showMessage:@"上传成功" view:self.view];
                } else {
                                        NSLog(@"===shibai");
                    //                    [MBProgressHUD showMessage:@"上传失败!" view:self.view];
                }
            }];
        }
    }];
    
    NSString * registrationID = DEF_GET_OBJECT(@"registrationID");

    if (registrationID) {
        
        [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"registration_id" WithUpdate_content:registrationID WithBlock:^(BOOL success, id responseData) {
            
        }];
    }
    
}

- (void)setupNSNoti{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeCouponView) name:@"clickCloseButton" object:nil];
}

- (void)setupUI{

    int tabHeight = (iPhoneX ? 44.f : 20.f);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - tabHeight - 20 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF8F9FA);
    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    TableViewHeader * headerView =  [[TableViewHeader alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 270 * SCREENH6)];
    // 设置header
    tableView.tableHeaderView = headerView;
    //    self.tableView.bounces = NO;
    //    self.tableView.estimatedRowHeight = 150 * SCREENH6;//估算高度
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"HomeListCell"];
    [self.tableView registerClass:[ActiveHeaderView class] forHeaderFooterViewReuseIdentifier:@"ActiveHeaderView"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self loadData];
    }];
    
    [self.view addSubview:self.tableView];
    

    UILabel * showLabel = [UILabel new];
    
    showLabel.textColor = ZRBlackColor;
    showLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    showLabel.text = @"暂无商品";
    showLabel.textAlignment = NSTextAlignmentCenter;
    showLabel.hidden = YES;
    
    self.showLabel = showLabel;
    
    [self.view addSubview:self.showLabel];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.goodlistArray.count == 0) {
        
        self.showLabel.hidden = NO;
    }else{
        
        self.showLabel.hidden = YES;
    }
    return self.goodlistArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
    if (cell == nil) {
        
        cell = [[HomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HomeListCell"];
    }
    
//    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeListCell" forIndexPath:indexPath];
    
    cell.model = self.goodlistArray[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 95 * SCREENH6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ActiveHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ActiveHeaderView"];
    
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HiddenBar;
    
    GoodsModel * model = self.goodlistArray[indexPath.row];
    GoodsDetailsViewController * detailVC = [GoodsDetailsViewController new];
    detailVC.ID = model.id;
    detailVC.infoType = [NSString stringWithFormat:@"%@",model.merchants_goods_type];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    ShowBar;
}

//-(void)createButton{
//    if (!_button) {
//        _window = [[UIApplication sharedApplication] keyWindow];
//        _window.backgroundColor = [UIColor whiteColor];
//        [_window addSubview:self.button];
//        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:
//                                       self action:@selector(locationChange:)];
//        pan.delaysTouchesBegan = YES;
//        [_button addGestureRecognizer:pan];
//    }
//}
//
//-(UIButton*)button{
//    if (!_button) {
//        _button = [UIButton buttonWithType:UIButtonTypeCustom];
////        _button.backgroundColor = [UIColor redColor];
//        [_button setImage:[UIImage imageNamed:@"全局浮动按钮"] forState:UIControlStateNormal];
//        _button.frame = CGRectMake(kScreenW - 65 * SCREENH6, 300 * SCREENH6, 65 * SCREENH6, 65 * SCREENH6);//初始在屏幕上的位置
//        //_button.layer.cornerRadius = 33;
//        //_button.layer.masksToBounds = YES;
//        [_button addTarget:self action:@selector(clickSeverceButton) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _button;
//}
//
//-(void)locationChange:(UIPanGestureRecognizer*)p{
//
//    CGFloat HEIGHT=_button.frame.size.height;
//    CGFloat WIDTH=_button.frame.size.width;
//    CGPoint panPoint = [p locationInView:[UIApplication sharedApplication].windows[0]];
//    if(p.state == UIGestureRecognizerStateChanged){
//        _button.center = CGPointMake(panPoint.x, panPoint.y);
//    }
//    else if(p.state == UIGestureRecognizerStateEnded){
//        if(panPoint.x <= kScreenW/2) {
//            if(panPoint.y <= 40+HEIGHT/2 && panPoint.x >= 20+WIDTH/2)  {
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(panPoint.x, HEIGHT/2);
//                }];
//            } else if(panPoint.y >= kScreenH-HEIGHT/2-40 && panPoint.x >= 20+WIDTH/2){
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(panPoint.x, kScreenH-HEIGHT/2);
//                }];
//            }  else if (panPoint.x < WIDTH/2+15 && panPoint.y > kScreenH-HEIGHT/2){
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(WIDTH/2, kScreenH-HEIGHT/2);
//                }];
//            }  else{
//                CGFloat pointy = panPoint.y < HEIGHT/2 ? HEIGHT/2 :panPoint.y;
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(WIDTH/2, pointy);
//                }];
//            }
//        } else if(panPoint.x > kScreenW/2)
//        {
//            if(panPoint.y <= 40+HEIGHT/2 && panPoint.x < kScreenW-WIDTH/2-20 ) {
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(panPoint.x, HEIGHT/2);
//                }];
//            }else if(panPoint.y >= kScreenH-40-HEIGHT/2 && panPoint.x < kScreenW-WIDTH/2-20) {
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(panPoint.x, kScreenH-HEIGHT/2);
//                }];
//            }else if (panPoint.x > kScreenW-WIDTH/2-15 && panPoint.y < HEIGHT/2) {
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(kScreenW-WIDTH/2, HEIGHT/2);
//                }];
//            } else{
//                CGFloat pointy = panPoint.y > kScreenH-HEIGHT/2 ? kScreenH-HEIGHT/2 :panPoint.y;
//                [UIView animateWithDuration:0.2 animations:^{
//                    self->_button.center = CGPointMake(kScreenW-WIDTH/2, pointy);
//                }];
//            }
//        }
//    }
//}


- (void)didLeftNavButton{
    
    UIView * backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    backView.backgroundColor = ZRBlackColor;
    backView.alpha = 0.4;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeCouponView)];
    backView.userInteractionEnabled = YES;
    [backView addGestureRecognizer:tapGR];
    
    self.backView = backView;
    
    [self.tabBarController.view addSubview:self.backView];
    
    int yValue;
    
    if (iPhoneX) {
        
        yValue = kStatusBarHeight + kNavHeight + 120 * SCREENH6;
    }else{
        
        yValue = kStatusBarHeight + 120 * SCREENH6;
    }
    
    self.couponView = [[CouponView alloc] initWithFrame:CGRectMake(15 * SCREENH6, yValue, 345 * SCREENH6, 400 * SCREENH6)];
    
    self.couponView.homeCouponViewDelegate = self;
    self.couponView.layer.cornerRadius = 5;
    self.couponView.layer.masksToBounds = YES;
    
    [self.tabBarController.view addSubview:self.couponView];
}

- (void)didRightNavButton{
    
    HiddenBar;
    
    SearchGoodsListViewController * searchVC = [SearchGoodsListViewController new];
    
    [self.navigationController pushViewController:searchVC animated:YES];
    
    ShowBar;
}


- (void)pushToBannerView:(NSNotification *)noti{
    
    BannerModel * model = noti.userInfo[@"model"];
    
    int is_link = [model.is_link intValue];
    int inside_or_outside = [model.inside_or_outside intValue];
    NSString * goods_type = [NSString stringWithFormat:@"%@",model.goods_type];
    NSString * url = [NSString stringWithFormat:@"%@",model.url];
    if (is_link == 1) {
        HiddenBar;
        if (inside_or_outside == 1) {

            if (url) {
               GoodsDetailsViewController * detailVC = [GoodsDetailsViewController new];
                detailVC.ID = url;
                detailVC.infoType = goods_type;
                [self.navigationController pushViewController:detailVC animated:YES];
            }
            
        }else{
            
            BannerWebViewViewController * webVC = [BannerWebViewViewController new];
            
            webVC.urlStr = url;
            
            [self.navigationController pushViewController:webVC animated:YES];
        }
        
        ShowBar;
    }
    
}


////开始定位
//- (void)startLocation {
//    
//    if ([CLLocationManager locationServicesEnabled]) {
//        //        CLog(@"--------开始定位");
//        self.locationManager = [[CLLocationManager alloc]init];
//        self.locationManager.delegate = self;
//        //控制定位精度,越高耗电量越
//        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
//        // 总是授权
//        [self.locationManager requestWhenInUseAuthorization];
//        self.locationManager.distanceFilter = 10.0f;
//        //        [self.locationManager requestAlwaysAuthorization];
//        [self.locationManager startUpdatingLocation];
//    }
//}
//
//
//- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//    if ([error code] == kCLErrorDenied) {
//        NSLog(@"访问被拒绝");
//    }
//    if ([error code] == kCLErrorLocationUnknown) {
//        NSLog(@"无法获取位置信息");
//    }
//}
////定位代理经纬度回调
//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
//    
//    CLLocation *newLocation = locations[0];
//
////    self.userLocation = newLocation;
//    
//    double lat = newLocation.coordinate.latitude;
//    double lon = newLocation.coordinate.longitude;
//    
//    NSString * latStr = [NSString stringWithFormat:@"%f",lat];
//    NSString * lonStr = [NSString stringWithFormat:@"%f",lon];
//    
//    DEF_SET_OBJECT(latStr, @"lat");
//    DEF_SET_OBJECT(lonStr, @"lon");
//}


- (void)changeGoodsListData:(NSNotification *)noti{
    
    
    NSString * ID = noti.userInfo[@"ID"];
    NSString * type = noti.userInfo[@"type"];
    if ([type isEqualToString:@"first"]) {
        
    }else{
        
       self.goodlistArray = nil;
    }
    self.ID = ID;
    
    [[ZRNetworkTool sharedTool] getGoodsListResultWithCategory:ID WithIs_merchants_get:@"0" WithBlock:^(BOOL success, id responseData) {
        
        NSLog(@"res===%@",responseData);
        if (success) {
            self.goodlistArray = [NSArray yy_modelArrayWithClass:[GoodsModel class] json:responseData[@"data"]];
            
            if (self.count == 1) {
                
                NSArray* testResult = [NSArray bg_arrayWithName:@"homeGoods"];
                if (testResult.count > 0) {
                    
                    [NSArray bg_clearArrayWithName:@"homeGoods"];
                    [self.goodlistArray bg_saveArrayWithName:@"homeGoods"];
                }else{
                    
                    [self.goodlistArray bg_saveArrayWithName:@"homeGoods"];
                }
            }
            
            self.count = self.count + 1;
        }
    }];
}

-(void)viewDidLayoutSubviews{
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-105 * SCREENH6);
    }];
    
}


- (void)removeCouponView{
    
    [self.backView removeFromSuperview];
    [self.couponView removeFromSuperview];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



- (UIView *)setupLineView{
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    return lineView;
}


//- (UIViewController *)getCurrentVC {
//
//    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
//    if (!window) {
//        return nil;
//    }
//    UIView *tempView;
//    for (UIView *subview in window.subviews) {
//        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
//            tempView = subview;
//            break;
//        }
//    }
//    if (!tempView) {
//        tempView = [window.subviews lastObject];
//    }
//
//    id nextResponder = [tempView nextResponder];
//    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
//        tempView =  [tempView.subviews firstObject];
//
//        if (!tempView) {
//            return nil;
//        }
//        nextResponder = [tempView nextResponder];
//    }
//    return  (UIViewController *)nextResponder;
//}


- (void)clickUseButtonWithShop_id:(NSString *)shop_id{
    
    if ([shop_id isEqualToString:@"0"]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"该券为全场通用券，在任何一家店铺都能使用"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        HiddenBar;
        ShopDetailsViewController * detailsVC = [ShopDetailsViewController new];
        detailsVC.ID = shop_id;
        [self.navigationController pushViewController:detailsVC animated:YES];
        ShowBar;
    }
    
    [self.backView removeFromSuperview];
    [self.couponView removeFromSuperview];
}


- (void)loadData{
    
//    self.goodlistArray = nil;
    
    [[ZRNetworkTool sharedTool] getGoodsListResultWithCategory:self.ID WithIs_merchants_get:@"0" WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            self.goodlistArray = [NSArray yy_modelArrayWithClass:[GoodsModel class] json:responseData[@"data"]];
        }
    }];
    
    [self.tableView.mj_header endRefreshing];
}



//开始定位
- (void)startLocation {
    
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        // 总是授权
        [self.locationManager requestWhenInUseAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        //        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *newLocation = locations[0];
    
    //    self.userLocation = newLocation;
    
    double lat = newLocation.coordinate.latitude;
    double lon = newLocation.coordinate.longitude;
    
    NSString * latStr = [NSString stringWithFormat:@"%f",lat];
    NSString * lonStr = [NSString stringWithFormat:@"%f",lon];
    
    DEF_SET_OBJECT(latStr, @"lat");
    DEF_SET_OBJECT(lonStr, @"lon");
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];;
    
    NSDictionary * dict = @{@"address_longitude":lonStr,@"address_latitude":latStr,@"lost_login_time":currentTimeString};
    
    
    [[ZRNetworkTool sharedTool] updateUserInfoAllWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res==%@",responseData);
    }];
}

@end
